import json
import os
import time

from .leetcode_operation import LeetCodeOperation


class QuestionHints(LeetCodeOperation):
    def __init__(self, requests_manager, base_url="https://leetcode.cn", **params):
        super().__init__(requests_manager, base_url)
        self.params = params.get('params')
        self.filename="question_hints.json"
        self.endpoint = 'graphql'

    def generate_payload(self):
        query_string = "\n    query questionHints($titleSlug: String!) {\n  question(titleSlug: $titleSlug) {\n    hints\n  }\n}\n    "
        return {
            "query": query_string,
            "variables": self.params,
            "operationName": "questionHints"
        }
        
    def parse_graphql_data(self, data):
        data = data.get('data', {}).get('question', {})
        return data
    
    # Execute Method
    def execute(self):
        data = self.fetch_data(self.endpoint, method='POST')
        data = self.parse_graphql_data(data)
        self.save_json(data, self.filename)

    def fetch_all_data(self, dest="QuestionHints", request_interval=1):
        slugs = self.read_all_title_slugs()
        dest_path = os.path.join(self.directory, dest)
        os.makedirs(dest_path, exist_ok=True)
        files = os.listdir(dest_path)
        exists_slugs = [slug.split(".")[0] for slug in files]
        question_content = []
        
        todo_list = [ slug for slug in slugs if slug not in exists_slugs]
        
        for slug in todo_list:
            self.params.update({'titleSlug': slug})
            self.logger.info(f"slug: {slug}")
            file_name = f"{slug}.json"
            data = self.fetch_data(self.endpoint, method='POST')
            parsed_data = self.parse_graphql_data(data)
            if parsed_data and parsed_data.get("hints"):
                self.save_json(parsed_data, os.path.join(dest, file_name))
